const { Server } = require("socket.io");

let history = [];//历史聊天记录{name:string,content:string,date:number}
let nextId = 1;//自动增长游客进入的序号
let users = new Set();//用户集合数组

const io = new Server({
  path: "/",
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

io.on("connection", (socket) => { 
  const username = "游客 " + nextId++
  users.add(username);

  //广播通知所有用户
  io.emit("$updateUser", [...users]);
  //发送聊天历史记录
  socket.emit("$history", history);
  //告知用户名
  socket.emit("$name", username);

  //广播聊天信息
  socket.on("$message", (content) => { 
    if (content === null) return;
    const msg = {
      name: username,
      content,
      date:Date.now()
    }
    history.push(msg);

    //广播消息
    socket.broadcast.emit("$message", msg);
  })

  socket.on('disconnect', () => {
    // 清除用户
    users.delete(username);
    // 广播通知所有用户
    socket.broadcast.emit('$updateUser', [...users]);
  });
})

io.listen(9528);
console.log(`Socket.io 聊天室已启动,端口号:9528`);